package com.cynteka.cyfoman.core;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: Sergey
 * Date: 17.07.11
 * Time: 14:24
 */
public class DefaultValueResolver implements ValueResolver {

    private static final String CALLING = "\\$\\{([^\\}]*)\\}";
    private static final Pattern CALLING_PATTERN = Pattern.compile(CALLING);

    private List<Function> functions;

    public List<Function> getFunctions() {
        return functions;
    }

    public void setFunctions(List<Function> functions) {
        this.functions = functions;
    }

    @Override
    public Object resolve(String value) {
        Matcher matcher = CALLING_PATTERN.matcher(value);
        int prev = 0;
        StringBuilder res = new StringBuilder();
        while (matcher.find()) {
            String functionName = matcher.group(1);
            Function function = getFunction(functionName);
            Object fValue = function.getValue();
            if (matcher.end() - matcher.start() == value.length()) {
                return fValue;
            } else {
                res.append(value.substring(prev, matcher.start()));
                res.append(fValue);
                prev = matcher.end();
            }

        }
        res.append(value.substring(prev, value.length()));
        return res.toString();
    }

    private Function getFunction(String name) {
        for (Function function : functions) {
            if (function.getName().equals(name)) {
                return function;
            }
        }
        throw new IllegalArgumentException("Unknown function " + name);
    }
}
